from zope.interface import Interface
from zope.interface import implements
from zope.component import getMultiAdapter
from Products.CMFCore.utils import getToolByName
from Acquisition import aq_inner
from plone.memoize.instance import memoize

from plone.app.portlets.portlets import base
from plone.portlets.interfaces import IPortletDataProvider

from zope import schema
from zope.formlib import form
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from my315ok.xtjxwcontents.interfaces.jiaxiao import Ijiaxiao

from my315ok.xtjxwcontents import xtjxwcontentsMessageFactory as _
from my315ok.products import productsMessageFactory as _a

from zope.i18nmessageid import MessageFactory
__ = MessageFactory("plone")

class Ischoolportlet(IPortletDataProvider):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """
    header = schema.TextLine(title=_a(u"Portlet header"),
                             description=_a(u"Title of the rendered portlet"),
                             required=True)    
    limit = schema.Int(title=_a(u"Limit"),
                       description=_a(u"Specify the maximum number of items to show in the portlet. "
                                       "Leave this blank to show all items."),
                       default=10,
                       required=False)
    cols = schema.Int(title=_a(u"cols"),
                       description=_a(u"Specify the cols number."),
                       required=False)

    wordsnum = schema.Int(title=_a(u"number"),
                       description=_a(u"Specify the maximum number of words to show as title. "
                                       "Leave this blank to show all items."),
                       default=12,
                       required=False)



class Assignment(base.Assignment):
    """Portlet assignment.

    This is what is actually managed through the portlets UI and associated
    with columns.
    """

    implements(Ischoolportlet)

    header=u""
    limit=10
    cols = 1
    wordsnum = 12


    def __init__(self, header=u"",limit=10, wordsnum=12, cols=1):
        self.header = header
        self.cols = cols
        self.wordsnum = wordsnum


    @property
    def title(self):
        """This property is used to give the title of the portlet in the
        "manage portlets" screen.
        """
        return __(u"schoolportlet")


class Renderer(base.Renderer):
    """Portlet renderer.

    This is registered in configure.zcml. The referenced page template is
    rendered, and the implicit variable 'view' will refer to an instance
    of this class. Other methods can be added and referenced in the template.
    """

    render = ViewPageTemplateFile('schoolportlet.pt')


    @property
    def available(self):
#        import pdb
#        pdb.set_trace()
        return bool(len(self.results("xiangtanshihexi")) >= 1)

    def ifrenderpanel(self,category):
        lenth = len(self.results(category))
        return bool(lenth >= 1)
                    
    @memoize
    def rows(self,category):
        total = len(self.results(category))
        cols = self.cols()
        out = int((total + cols - 1)/cols)             
#        rows = self.data.rows
        return out
        
    def cols(self):
        cols = self.data.cols
        return cols
    

    def results(self,category):
        """ Get the actual result brains from the collection. 
            This is a wrapper so that we can memoize if and only if we aren't
            selecting random items."""
        
        return self.fetchinfo(category)

      
        
    @memoize
    def fetchinfo(self,category):
        context = aq_inner(self.context)
        catalog = getToolByName(context, 'portal_catalog')        
        lm = self.data.limit
        if lm == None:
            lm = self.rows(category) * self.cols()       
        result = []
        
        brains = catalog(object_provides=Ijiaxiao.__identifier__,
                             district=category,
                             review_status='published',
                             sort="modified",
                             sort_order='reverse'
                             )
        
        if lm > 0 and lm < len(brains):
            brains = brains[:lm]
        return brains
    @memoize   
    def main_parameters(self,category):
        """ fetch product parameters""" 
#        import pdb
#        pdb.set_trace()             
        brains = self.results(category)

        goods = []

        if len(brains) >0:            
            for bs in brains:              
                tmp = self.add_paras(bs)
                goods.append(tmp)
        return goods
    
    # here is set local varible item avoid by overed.
    @memoize
    def add_paras(self,obj):
        """given a multiproducts brain,fetch products parameters"""
#        import pdb
#        pdb.set_trace()
        try:
            le = self.data.wordsnum
        except:
            le = 36
        item={}
        item['title'] =  self.cropTitle(obj.Title, le)        

        item['url'] =  obj.getURL()

        return item      

    @memoize
    def cropTitle(self,text, length, ellipsis='...'):
        if length == 0 or length == None:
            return text
        context = aq_inner(self.context)
        pview = getMultiAdapter((context,self.request),name=u"plone")
#        pview = getMultiAdapter((self.parent(), self.request), name=u'earthqk_event_view')
        croped = pview.cropText(text, length)
        return croped 

class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(Ischoolportlet)

    def create(self, data):
        return Assignment(**data)


# NOTE: IF this portlet does not have any configurable parameters, you can
# remove this class definition and delete the editview attribute from the
# <plone:portlet /> registration in configure.zcml

class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(Ischoolportlet)
